<?php

/**
 * 购物车类
 * 使用COOKIE保存一个经过serialize后并base64_encode的二维数组
 * array(
 *      array(...),
 *      array(...),
 * )
 * @author Administrator
 */
class Cart {

    //名称
    public $cookieName = 'cart';
    //时间
    public $time = 86400;
    //域名
    public $domin = null;
    //路径
    public $path = '/';
    //购物车内容
    public $orders = array();

    //初始货购物车
    public function __construct($cookieNmae = 'cart', $time = 86400, $path = '/', $domin = null) {
        $this->cookieName = $cookieNmae;
        $this->time = $time;
        $this->path = $path;
        $this->domin = $domin;
        $this->orders = $this->cartInfo();
    }

    /**
     * 加入购物车
     * @param array $product 
     */
    public function append($product) {
        $key = md5(print_r($product, true));
        $this->orders[$key] = $product;
        return setcookie($this->cookieName, $this->encodeCart($this->orders), time() + $this->time, $this->path, $this->domin);
    }

    /**
     * 删除购物车中产品
     * @param string $key
     * @return bool
     */
    public function remove($key) {
        unset($this->orders[$key]);
        return setcookie($this->cookieName, $this->encodeCart($this->orders), time() + $this->time, $this->path, $this->domin);
    }

    /**
     * 修改产品数量
     * @param string $key
     * @param int $num
     * @return type
     */
    public function updateNum($key, $num) {
        if ($this->orders[$key]) {
            $this->orders[$key]['num'] = $num;
            return setcookie($this->cookieName, $this->encodeCart($this->orders), time() + $this->time, $this->path, $this->domin);
        } else {
            return false;
        }
    }

    /**
     * 清空购物车
     */
    public function resetCart() {
        return setcookie($this->cookieName, NULL, time() - 3600, '/');
    }

    /**
     * 获取购物车内容
     * @return array 
     */
    public function cartInfo() {
        if (isset($_COOKIE[$this->cookieName])) {
            return $this->decodeCart($_COOKIE[$this->cookieName]);
        } else {
            return null;
        }
    }

    /**
     * 购物车中产品数量
     * @return int
     */
    public function cartNum() {
        return count($this->orders);
    }

    /**
     * 加密购物车内容 
     * @param array $orders
     * @return string
     */
    public function encodeCart($orders) {
        return base64_encode(serialize($orders));
    }

    /**
     * 解密内容
     * @param string $str
     * @return array
     */
    public function decodeCart($str) {
        return unserialize(base64_decode($str));
    }

}
